﻿using Artech.Common.Properties;
using Microsoft.Practices.Unity.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace Artech.Core
{
    public class StatefulEntryCollection<T> : IEnumerable<T> where T : StatefulEntry
    {
        private List<T> list = new List<T>();
        public StatefulEntryCollection()
        { }
        public StatefulEntryCollection(IEnumerable<T> entries)
        {
            Guard.ArgumentNotNull(entries, "entries");
            foreach (T entry in entries)
            {
                list.Add(entry);
            }
        }

        public void Add(T entry)
        {
            Guard.ArgumentNotNull(entry, "entry");
            if (null != entry.Parent || entry.State != EntryState.Detached)
            {
                throw new ArgumentException(CoreResources.ExceptionNotIndepedentEntry, "entry");
            }
            entry.State = EntryState.Added;
            entry.Parent = this;
            list.Add(entry);
        }

        public void Remove(T entry)
        {
            Guard.ArgumentNotNull(entry, "entry");
            list.Remove(entry);
            entry.Parent = null;
            entry.State = EntryState.Detached;
        }

        public IEnumerator<T> GetEnumerator()
        {
            return list.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return list.GetEnumerator();
        }
    }
}
